﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace ControlPanelWeb.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            ViewData["Trace"] = GetTraceData();
            return View();
        }

        private string GetTraceData()
        {
            // http://webcache.googleusercontent.com/search?q=cache:0x_9WsVrfwwJ:www.driis.dk/%3Ftag%3D%257B34262CC3-F7DD-4631-BD96-D748D735B6EA%257D+profiler.GetType().GetMethod(%22GetData%22&cd=1&hl=en&ct=clnk
            // http://stackoverflow.com/questions/3856438/redirecting-the-trace-axd-output

            // profiler requests
            var requests = GetProfileData();

            string result = "";
            foreach (var request in requests)
            {
                result += request.ToString();
            }
            return result;

            //// profiler.PageOutput = true;
            //profiler.GetType().GetProperty("PageOutput", evilFlags)
            //    .GetSetMethod(true).Invoke(profiler, new object[] { true });

            //// this.ProcessRequestEndTrace();
            //typeof(Page).GetMethod("ProcessRequestEndTrace", evilFlags)
            //    .Invoke(this, null);

            //// profiler.PageOutput = false;
            //profiler.GetType().GetProperty("PageOutput", evilFlags)
            //    .GetSetMethod(true).Invoke(profiler, new object[] { false });


            //return "trace output";
        }

        private object GetProfiler()
        {
            Type runtimeType = typeof(HttpRuntime);
            PropertyInfo profileProperty = runtimeType.GetProperty("Profile",
                                                                   BindingFlags.NonPublic | BindingFlags.Static);
            if (profileProperty != null)
            {
                return profileProperty.GetValue(null, null);
            }

            throw new ApplicationException("Reflection to get profiler instance failed.");
        }

        private IList GetProfileData()
        {
            var profiler = GetProfiler();
            Type profilerType = profiler.GetType();
            MethodInfo method = profilerType.GetMethod("GetData", BindingFlags.Instance | BindingFlags.NonPublic);
            return (IList) method.Invoke(profiler, null);
        }
    }
}
